package com.leon.service;

import com.leon.domain.auth.ApiRequest;
import com.leon.domain.auth.AuthToken;
import com.leon.domain.auth.Storage;

public class AuthServiceImpl implements AuthService {

    private Storage storage;

    public AuthServiceImpl(Storage storage) {
        this.storage = storage;
    }


    public void auth(String url) {
        ApiRequest apiRequest = ApiRequest.buildFromNewUrl(url);
        auth(apiRequest);
    }

    public void auth(ApiRequest apiRequest) {
        String token = apiRequest.getToken();
        String appId = apiRequest.getAppId();
        String originUrl = apiRequest.getAppId();
        long timestamp = apiRequest.getTimestamp();
        AuthToken authToken = new AuthToken(token, timestamp);
        if (authToken.isExpire()) {
            throw new RuntimeException("Token is Expired");
        }
        String password = storage.getFromStorage(appId);
        AuthToken tokenFromServer = AuthToken.generateToken(password, originUrl, timestamp, appId);
        if (!tokenFromServer.match(authToken)) {
            throw new RuntimeException();
        }
    }
}
